﻿using Android.Graphics.Drawables;
using System;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(Button), typeof(Games.Droid.ControlRenders.NormalButtonRender))]
namespace Games.Droid.ControlRenders
{
    class NormalButtonRender : ButtonRenderer
    {
        public NormalButtonRender(Android.Content.Context context) : base(context)
        {

        }
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
            var stack = e.NewElement as Button;
            if(stack == null)
            {
                return;
            }
            GradientDrawable.Orientation orientation = GradientDrawable.Orientation.TopBottom;
            var endColor = Xamarin.Forms.Color.Gainsboro;
            var middleRate = 0.75;

            var selector = new StateListDrawable();
            var enanablecolors = WithMiddleColor(stack.BackgroundColor, endColor, middleRate);
            var shapeEnabled = new GradientDrawable(orientation, enanablecolors);
            shapeEnabled.SetCornerRadius(stack.CornerRadius);
            selector.AddState(EnabledStateSet.ToArray(), shapeEnabled);

            var disanablecolors = WithMiddleColor(Xamarin.Forms.Color.Gray, endColor, middleRate);
            var shapeDisabled = new GradientDrawable(orientation, disanablecolors);
            shapeDisabled.SetCornerRadius(stack.CornerRadius);
            selector.AddState(EmptyStateSet.ToArray(), shapeDisabled);

            this.Control.SetBackground(selector);
        }

        protected static int[] WithMiddleColor(Xamarin.Forms.Color start, Xamarin.Forms.Color end, double middleRate)
        {
            Func<double, double, double, double> get = (s, e, r) => Math.Min(Math.Max(s + (e - s) * (1 - r), 0), 1);
            var middle = Xamarin.Forms.Color.FromRgba(get(start.R, end.R, middleRate),
                get(start.G, end.G, middleRate),
                get(start.B, end.B, middleRate),
                get(start.A, end.A, middleRate));
            return new int[] { start.ToAndroid().ToArgb(), middle.ToAndroid().ToArgb(), end.ToAndroid().ToArgb() };
        }
    }
}